package com.star.controller.user;

import com.star.constant.StatusConstant;
import com.star.entity.Setmeal;
import com.star.result.Result;
import com.star.service.SetmealService;
import com.star.vo.DishItemVO;
import com.star.vo.DishVO;
import com.star.vo.SetmealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userSetmealController")
@RequestMapping("/user/setmeal")
@Slf4j
@Api(tags ="C端套餐管理相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate<String, List<Setmeal>> redisTemplate;

    /**
     * 根据商家id查询套餐
     * @param businessId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据商家id查询套餐")
//    @Cacheable(value = "setmealCache", key = "#businessId")  //key:setmealCache::businessId
    public Result<List<Setmeal>> list(Long businessId){
        log.info("根据商家id查询套餐{}",businessId);
        // 构造redis中的key
        String key = "setmeal_" + businessId;

        // 判断redis中是否存在菜品数据
        List<Setmeal> setmealList;
        setmealList = redisTemplate.opsForValue().get(key);

        // 存在
        if(setmealList != null && !setmealList.isEmpty()){
            return Result.success(setmealList);
        }

        // 不存在，查询数据库，并把数据注入redis
        Setmeal setmeal = new Setmeal();
        setmeal.setBusinessId(businessId);
        setmeal.setStatus(StatusConstant.ENABLE);

       setmealList = setmealService.getBySetmeal(setmeal);

        redisTemplate.opsForValue().set(key, setmealList);
        return Result.success(setmealList);
    }

    /**
     * 根据套餐id查询套餐信息以及包含的菜品
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    @ApiOperation("根据套餐id查询包含的菜品")
    public Result<SetmealVO> getDishListById(@PathVariable Long id){
        log.info("根据套餐id查询包含的菜品{}", id);
        SetmealVO setmealVO = setmealService.getSetmealDishById(id);
        return Result.success(setmealVO);
    }
}
